package com.app.micaihu.utils;

import android.text.TextUtils;

import com.app.micaihu.configure.AppConfigTools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * 文件缓存工具类
 * Created by linkai on 2016/7/27.
 */
public class FileCacheUtils {

    private String cacheFileFolder;
    private File mCacheDefaultFile;//默认的缓存文件夹

    private static FileCacheUtils mfileCaheUtils;

    public static FileCacheUtils getInstance(){
        if(mfileCaheUtils == null){
            mfileCaheUtils = new FileCacheUtils();
        }
        return mfileCaheUtils;
    }

    private FileCacheUtils(){
        if(TextUtils.isEmpty(cacheFileFolder)){
            cacheFileFolder = AppConfigTools.NEWS_OFF_LINE;
        }
    }

    /**
     * 重置配置
     */
    public void reset(){
        cacheFileFolder = AppConfigTools.NEWS_OFF_LINE;
    }

    /**
     * 获取缓存数据
     * @param url
     * @return
     */
    public String readCacheData(String url){
        //通过url获取缓存文件
        File file = getCacheFileByUrl(url);
        //将缓存文件的内容转字符串
        String s = file2String(file, null);
        return s;
    }

    /**
     * 存储缓存数据
     * @param url
     * @param resStr
     */
    public void writeCacheData(final String url,final String resStr){
        //存储缓存数据
        new Thread(){
            @Override
            public void run() {
                File file = getCacheFileByUrl(url);
                string2File(resStr,file);
            }
        }.start();

    }

    /**
     * 返回缓存文件夹
     *
     * @return
     */
    public File getCacheFile() {
        if(mCacheDefaultFile == null){
            mCacheDefaultFile = new File(cacheFileFolder);
        }
        if (mCacheDefaultFile != null && !mCacheDefaultFile.exists()) {
            mCacheDefaultFile.mkdirs();
        }
        return mCacheDefaultFile;
    }

    /**
     * 通过网址得到对应的缓存文件
     *
     * @param url
     * @return
     */
    public synchronized  File getCacheFileByUrl(String url) {
        if(TextUtils.isEmpty(url)){
            return null;
        }
        File offFile = getCacheFile();
        if (offFile == null)
            return null;
        String s =  url.replaceAll("[^(a-zA-Z0-9)]", "");
        File file = new File(offFile.getAbsolutePath()+File.separator+s);
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return file;
    }

    /**
     * 将字符串写入指定文件
     *
     * @param res
     *            原字符串
     *            文件路径
     * @return 成功标记
     */
    public synchronized  boolean string2File(String res, File file) {
        if(TextUtils.isEmpty(res) || file == null){
            return false;
        }
        boolean flag = false;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            char buf[] = new char[4096]; // 字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
                bufferedWriter.flush();
            }
            flag=true;
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * 文本文件转换为指定编码的字符串
     *
     * @param file
     *            文本文件
     * @param encoding
     *            编码类型
     * @return 转换后的字符串
     * @throws IOException
     */
    public static String file2String(File file, String encoding) {
        if(file == null){
            return null;
        }
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {
            if (encoding != null && !"".equals(encoding)) {
                reader = new InputStreamReader(new FileInputStream(file),
                        encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(file));
            }
            // 将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        // 返回转换结果
        if (writer != null)
            return writer.toString();
        else
            return null;
    }

}
